<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/9/15
 * Time: 下午3:46
 */

class CrmUserController extends BaseController {
    /*
         * 用户申请短信验证码
         *
         * */
    public function login()
    {
        $validator = Validator::make(Input::all(),
            array(
                'userid' => 'required',
                'password' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("crm_error.login_args_error_1001");
                break;
            }
            //获取手机号
            $userid = Input::get('userid');
            $password = Input::get('password');
            $callback = Input::get('callback');

            $user_data = SystemUser::getUser($userid,$password);
            if(is_null($user_data)){
                $response = Lang::get("crm_error.login_user_not_exist_error_1002");
                break;
            }else{
                $token = md5($userid.$user_data->id.time());
                try {
                    SystemUser::saveUserToken($user_data->id,$token);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "crm" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.user_sms_check_code_create_error_1002");
                    break;
                }

                //组织返回
                $response = array(
                    'code' => 0,
                    'msg' => 'ok',
                    'result' => array(
                        'url' => 'http://test.anhui.com',
                        'token' => $token,
                        'user_id' => $user_data->id,
                    ));
            }
        } while (false);

        if(is_null($callback)){
            $response = json_encode($response);
        }else{
            $response = $callback . '(' . json_encode($response) . ')';
        }
        Log::info("info", array("system" => "crm" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return $response;
    }
}